package org.springboot.sample.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.springboot.sample.dao.UserDao;
import org.springboot.sample.po.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;


@Repository
public class UserDaoImpl implements UserDao {
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	 /**
	  * 判断当前用户是否存在
	 * @param user
	 * @return
	 */
	public Boolean isExistence(User user) {
        String sql = "select * from t_user where username=? and password=?";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, user.getUsername(),user.getPassword());
        //User list = jdbcTemplate.queryForObject(sql, new UserRowMapper(), user.getUsername(),user.getPassword());
        if(list.isEmpty()){
        	return false;
        }
        return true;
	}
	
	/**
	 * 查询当前系统中所有用户
	 * @return
	 */
	public List<User> findAll(){
		String sql = "select * from t_user";
		return jdbcTemplate.query(sql, new UserRowMapper());
	}
	
	/**
	 * 增加记录
	 */
	public void addUser(User user){
		String sql = "insert into t_user values(null,?,?)";
		jdbcTemplate.update(sql,user.getUsername(),user.getPassword());
	}
	
	/**
	 * 修改姓名
	 * @param user
	 */
	public void updateUserName(int userId,String updateUsername){
		String sql = "update t_user set username =? where id=?";
		jdbcTemplate.update(sql, updateUsername,userId);
	}
	
	public int findIdByNameAndPassword(User user){
		String sql = "select * from t_user where username=? and password=?";
		User u = jdbcTemplate.queryForObject(sql, new UserRowMapper(), user.getUsername(),user.getPassword());
		return u.getId();
	}
	@Override
	public void deleteUsersById(int id) {
		String sql = "delete from t_user where id=?";
		jdbcTemplate.update(sql, id);
	}
	 
	class UserRowMapper implements RowMapper<User> {
	     //rs为返回结果集，以每行为单位封装着
	     public User mapRow(ResultSet rs, int rowNum) throws SQLException {
	         User user = new User();
	          user.setId(rs.getInt("id"));
			  user.setUsername(rs.getString("username"));
			  user.setPassword(rs.getString("password"));
		      return user;
		}
			  
	}
}
